﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Trentacular.SharePoint.Util;
using Trentacular.SharePoint.Web.UI.WebParts;

namespace Trentacular.SharePoint.Web.UI.WebControls
{
    public class SelfRedirectingViewSelector : ToolBarMenuButton
    {
        public string ViewQueryStringKey { get; set; }

        private string _baseNavigateUrl;
        private string BaseNavigateUrl
        {
            get
            {
                if (_baseNavigateUrl == null)
                {
                    var request = Context.Request;
                    var queryParams = UrlUtils.GenerateQueryStringCollection(request.RawUrl);
                    queryParams.Remove(ViewQueryStringKey);

                    _baseNavigateUrl = UrlUtils.AppendQueryString(request.Path, queryParams);
                }
                return _baseNavigateUrl;
            }
        }

        protected override void AddMenuItems()
        {
            foreach (SPView view in RenderContext.List.Views)
            {
                if (!ListViewWebPart.IsViewAvailableForSelection(view))
                    continue;

                var menuItem = new MenuItemTemplate
                {
                    Text = view.Title,
                    ClientOnClickNavigateUrl = UrlUtils.AppendQueryStringPair(BaseNavigateUrl, ViewQueryStringKey, view.ID.ToString())
                };

                base.MenuTemplateControl.Controls.Add(menuItem);
            }
        }

        public override string Text
        {
            get
            {
                return RenderContext.ViewContext.View.Title;
            }
        }

        protected override void CreateChildControls()
        {
            if (string.IsNullOrEmpty(base.AccessKey))
            {
                base.AccessKey = SPResource.GetString("ViewSelectorMenuOpenAK", new object[0]);
            }

            base.CreateChildControls();

            base.MenuControl.HoverCellActiveCssClass = "ms-viewselectorhover";
            base.MenuControl.HoverCellInActiveCssClass = "ms-viewselector";
            base.MenuControl.ArrowImageUrl = "/_layouts/images/blank.gif";
            base.MenuTemplateControl.CompactMode = true;
        }
    }
}
